import { runCmdSync } from "../utils/runCmd.js";
import getPkgToolsConfig, {
  getPackageJson,
} from "../utils/getPkgToolsConfig.js";
import { getMsgByCard, postToRobot } from "../utils/postRobot.js";
import ora from "ora";
const {
  robotConfig = {
    robotUrl: "",
    packageName: "",
    robotDetailUrl: "",
  },
} = await getPkgToolsConfig();

/**
 * 向机器人推送消息
 * https://www.feishu.cn/hc/zh-CN/articles/410063847664
 */
const robot = () => {
  /**
   * 推送内容
   * 包名 [发布|删除|废弃] 版本号
   * 发布人
   * 更新内容（changelog）
   * 查看详情（www.npmjs.com/package/packageName）
   */
  const robotMsgSpinner = ora("推送机器人消息...");
  robotMsgSpinner.start();
  console.log(" ");
  try {
    // 操作人姓名
    const { stdout: operatorName } = runCmdSync("npm", ["whoami"]);
    // 当前版本号
    const { version, name } = getPackageJson();
    // 更新内容（changelog）git diff
    const { stdout: diff } = runCmdSync("git", [
      "diff",
      "HEAD^",
      "--",
      "CHANGELOG.md",
    ]);
    const changeLogStr = diff
      .split(/[\n\r]/)
      .filter((line) => line.startsWith("+") && !line.startsWith("++"))
      .map((line) => line.substring(1))
      .filter((line) => !!line);

    postToRobot({
      url: robotConfig.robotUrl,
      data: getMsgByCard({
        packageName: robotConfig.packageName || name,
        version,
        who: operatorName,
        changeLog: changeLogStr.join("\n"),
        detailUrl: robotConfig.robotDetailUrl,
      }),
    }).then(() => {
      robotMsgSpinner.succeed("推送机器人消息成功");
    }).catch((err) => {
      console.error(err);
      robotMsgSpinner.fail("推送机器人消息失败");
    })
  } catch (err) {
    console.error(err);
    robotMsgSpinner.fail("推送机器人消息失败");
  }
};
export default robot;
